package com.flame.file.service;

import java.util.List;

import com.flame.auth.core.context.AuthContextHolder;
import com.flame.core.id.IdWorker;
import com.flame.core.utils.DateUtils;
import com.flame.core.utils.FileUtils;
import com.flame.file.config.FileConfigurationProperties;
import com.flame.file.constant.FileConstants;
import com.flame.file.controller.vo.StaticFileInfoVo;
import com.flame.file.entity.StaticFileInfo;
import com.flame.file.mapper.StaticFileInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * flame_sys_static_file_info 系统静态资源表
 *
 * @author 吴欣童
 * @since 2023-03-16 11:00:18
 */
@Service
public class StaticFileInfoService {

    @Autowired
    private FileConfigurationProperties properties;

    @Autowired
    private StaticFileInfoMapper staticFileInfoMapper;

    @Autowired
    private IdWorker idWorker;

    public List<StaticFileInfo> pageStaticFileInfo(StaticFileInfoVo staticFileInfoVo) {
        return staticFileInfoMapper.page(staticFileInfoVo);
    }

    public void deleteStaticFileInfo(Long fileId) {
        StaticFileInfo dbFileInfo = staticFileInfoMapper.findById(fileId);
        if (dbFileInfo != null) {
            FileUtils.delete(dbFileInfo.getFileLocation());
        }
        staticFileInfoMapper.deleteById(fileId);
    }

    public String save(MultipartFile file) {
        long fileId = idWorker.nextId();
        String fileFullName = file.getOriginalFilename();
        String fileName = FileUtils.getFileName(fileFullName);
        String fileType = FileUtils.getFileType(fileFullName);

        String localFilePath = FileUtils.writeFile(properties.getDir(), fileName + "-" + fileId + "." + fileType, file);

        String md5 = FileUtils.md5(localFilePath);

        StaticFileInfo fileInfo = new StaticFileInfo();
        fileInfo.setFileId(fileId);
        fileInfo.setFileStorageType(FileConstants.STORAGE_TYPE_LOCAL);
        fileInfo.setFileName(fileName);
        fileInfo.setFileType(fileType);
        fileInfo.setFileLocation(localFilePath);
        fileInfo.setMd5(md5);
        fileInfo.setUploadTime(DateUtils.currentDateTime());
        fileInfo.setUploadUser(AuthContextHolder.getContext().getAccount());
        staticFileInfoMapper.insert(fileInfo);
        return "/static/file?fileId=" + fileId;
    }

    public StaticFileInfo getFileInfo(Long fileId) {
        return staticFileInfoMapper.findById(fileId);
    }
}
